import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/config/config.dart';
import 'package:yp/helper.dart';
import 'package:yp/services/api.dart';

import '../../../router.dart';
import 'state.dart';

import 'package:yp/pages/address_selector/address_model.dart';

class CommoditySearchLogic extends GetxController {
  final state = CommoditySearchState();

  @override
  void onInit() {
    super.onInit();

    state.contentTextController = TextEditingController();
    state.contentFocusNode = FocusNode();

    getHistorySearchKeyList();
    getRealTimeHotSearchList(false);
    getHotSearchList();

    Map<String, dynamic> params = {
      "shop_id": SpUtil.getInt("storeShopNum"),
      "type": "defword"
    };

    Api.getRealTimeHotSearchList(params).listen((event) {
      print("获取热搜列表========：$event");
      if (event["code"] == 0) {
        if (event["word_title"] != null) {
          // state.hotSearchTitle = event["word_title"];
        }
        if (event["word"] != null) {
          List list = event["defword"];
          int len = list.length;
          int rand = Random().nextInt(len);
          state.keyword = list[rand]["defword_name"];
          // state.realTimeSearchList = list;
        }
        update();
      }
    }, onDone: () {});
  }

  /// 获取历史搜索列表
  void getHistorySearchKeyList() {
    var objectList = SpUtil.getStringList(Config.HISTORY_SEARCH_KEYWORD_LIST);
    if (objectList != null && objectList.length > 0) {
      state.historicalSearchList = objectList;
      update();
    }
  }

// 获取广告内容
  void getAdvertising() {
    print('获取广告列表');
    var params = {
      'adv_category': '1',
      'page_num': 1,
      'page_size': 10,
      'status_num_id': 3
    };
    Api.getAdvertising(params).listen((event) {
      if (event["code"] == 0 && event["list"] != null) {
        state.advertising = event['list'];
      } else {
        state.advertising = [];
      }
      update();
    });
  }

  /// 获取实时热搜列表
  void getRealTimeHotSearchList(bool isBool) {
    Map<String, dynamic> params = {
      "shop_id": SpUtil.getInt("storeShopNum"),
      "type": "word"
    };
    if (isBool == true) {
      EasyLoading.show();
    }
    Api.getRealTimeHotSearchList(params).listen((event) {
      EasyLoading.dismiss();
      print("获取热搜列表========：$event");
      if (event["code"] == 0) {
        if (event["word_title"] != null) {
          state.hotSearchTitle = event["word_title"];
        }
        if (event["word"] != null) {
          List list = event["word"];
          state.realTimeSearchList = list;
        }
        update();
      }
    }, onDone: () {
      EasyLoading.dismiss();
    });
  }

  /// 删除历史搜索关键词
  void removeHistorySearchKeyword() {
    SpUtil.putStringList(Config.HISTORY_SEARCH_KEYWORD_LIST, []);
    state.historicalSearchList = [];
    update();
  }

  /// 添加历史搜索关键词
  void addHistorySearchKeyword({String hotWord}) {
    if (hotWord != null) {
      state.contentTextController.text = hotWord;
      update();
    }
    if (state.contentTextController.text.isEmpty) {
      toast("请输入店内商品名称");
      return;
    }
    String keyword = state.contentTextController.text;

    if (state.historicalSearchList.contains(keyword)) {
      state.historicalSearchList.remove(keyword);
      state.historicalSearchList.insert(0, keyword);
    } else {
      if (state.historicalSearchList.length >= 10) {
        state.historicalSearchList.removeLast();
      }
      state.historicalSearchList.insert(0, keyword);
    }
    SpUtil.putStringList(
        Config.HISTORY_SEARCH_KEYWORD_LIST, state.historicalSearchList);
    update();
  }

  /// 获取热搜榜单
  void getHotSearchList() {
    getCurrentLocationInfo(success: (data) {
      var addressInfo = data['addressInfo'];
      Map<String, dynamic> params = {
        "shop_id": SpUtil.getInt("storeShopNum"),
        "use_platform": 2,
        "prv_num_id": addressInfo['prv_num_id'],
        "city_num_id": addressInfo['city_num_id'],
        "city_area_num_id": addressInfo['city_area_num_id'],
        "town_num_id": addressInfo['town_num_id'],
        "maplocation_x": addressInfo['maplocation_x'],
        "maplocation_y": addressInfo['maplocation_y'],
        "page_no": 1,
        "page_size": 10,
        "order_by": "sold_quantity desc",
        "access_token": SpUtil.getString("token")
      };
      Api.getHotSearchList(params).listen((event) {
        print("获取热搜榜单========：$event");
        if (event["code"] == 0) {
          if (event["lists"] != null) {
            List list = event["lists"];
            state.hotSearchList = list;
            update();
          }
        }
      });
    });
  }

  /// 取消搜索
  void cancelSearch() {
    state.contentTextController.clear();
    update();
  }

  void changeSearchType(int index) {
    state.searchType = index;
    state.showSearchList = !state.showSearchList;
    update();
  }
}
